<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="98px"
    >
      <el-form-item label="区域名称" prop="regionName">
        <el-input
          v-model="queryParams.regionName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入门店名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收支名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入收支名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="时间" prop="searchTime">
        <el-date-picker
          @change="getTime"
          v-model="searchTime"
          type="daterange"
          align="right"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="收支类型" prop="typeId">
        <el-select
          v-model="queryParams.typeId"
          clearable
          filterable
          placeholder="请选择"
          @change="handleQuery"
        >
          <el-option label="收入" :value="1"></el-option>
          <el-option label="支出" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否参与统计" prop="isStatistics">
        <el-select
          v-model="queryParams.isStatistics"
          clearable
          filterable
          placeholder="请选择"
          @change="handleQuery"
        >
          <el-option label="是" :value="1"></el-option>
          <el-option label="否" :value="0"></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="区域id" prop="regionId">
        <el-input
          v-model="queryParams.regionId"
          placeholder="请输入区域id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="门店id" prop="storeId">
        <el-input
          v-model="queryParams.storeId"
          placeholder="请输入门店id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入门店名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收支类型id" prop="typeId">
        <el-input
          v-model="queryParams.typeId"
          placeholder="请输入收支类型id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收支类型名称" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入收支类型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="金额" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-input
          v-model="queryParams.state"
          placeholder="请输入状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['business:income:query']"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:income:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:expenses:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:income:del']"
          >批量删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="handleImport"
          v-hasPermi="['system:expenses:import']">导入</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:expenses:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="expensesList"
      max-height="650px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="所属区域" align="center" prop="regionName" />
      <!-- <el-table-column label="门店id" align="center" prop="storeId" /> -->
      <el-table-column label="所属门店" align="center" prop="storeName" />
      <el-table-column label="收支名称" align="center" prop="name" />
      <!-- <el-table-column label="区域id" align="center" prop="regionId" /> -->
      <el-table-column label="金额" align="center" prop="price" />
      <!-- <el-table-column label="收支类型id" align="center" prop="typeId" /> -->
      <el-table-column label="收支类型" align="center" prop="typeId">
        <template slot-scope="scope">
          {{ typeConfig[scope.row.typeId] }}
        </template>
      </el-table-column>
      <el-table-column
        label="是否参与统计选择"
        align="center"
        prop="isStatistics"
      >
        <template slot-scope="scope">
          {{ scope.row.isStatistics === 1 ? "是" : "否" }}
        </template>
      </el-table-column>
    
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建人"   align="center"  prop="createBy" />
      <el-table-column label="创建时间"   align="center"  prop="createTime" />
      <el-table-column label="修改人"   align="center"  prop="updateBy" />
      <el-table-column label="修改时间"   align="center"  prop="updateTime" />
      <!-- <el-table-column label="状态" align="center" prop="state" /> -->
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, 1)"
            v-hasPermi="['business:income:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:income:del']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row, 2)"
            v-hasPermi="['business:income:views']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改收支记录对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :disabled="disabled"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="收支名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入收支名称"
                style="width: 222px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="适用区域" prop="regionId" label-width="150px">
              <el-select
                clearable
                v-model="form.regionId"
                @change="changeRegion"
              >
                <el-option
                  v-for="(item, index) of region"
                  :key="index"
                  :label="item.value"
                  :value="item.key"
                  >{{ item.value }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="适用门店" prop="storeId">
              <el-select clearable v-model="form.storeId" @change="changeStore">
                <el-option
                  v-for="(item, index) of store"
                  :key="index"
                  :label="item.value"
                  :value="item.key"
                  >{{ item.value }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="price" label-width="150px">
              <el-input
                v-model="form.price"
                placeholder="请输入金额"
                style="width: 222px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收支类型" prop="typeId">
              <el-select clearable v-model="form.typeId">
                <el-option
                  v-for="(item, index) of typeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  >{{ item.label }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="是否参与统计选择"
              prop="isStatistics"
              label-width="150px"
            >
              <el-select clearable v-model="form.isStatistics">
                <el-option
                  v-for="(item, index) of statisticOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  >{{ item.label }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="凭证" prop="voucher">
              <image-upload v-model="form.voucher" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                v-model="form.remark"
                placeholder="请输入备注"
                style="width: 300px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="title != '查看收支记录'">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listExpenses,
  getExpenses,
  delExpenses,
  addExpenses,
  updateExpenses,
  listMemberRegion,
  listMemberStore,
} from "@/api/system/expenses";
import { getToken } from "@/utils/auth";

export default {
  name: "Expenses",
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "当月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              const now = new Date();
              // 设置当前月份的第一天（00:00:00）
              now.setDate(1);
              now.setHours(0, 0, 0, 0);
              start.setTime(
                start.getTime() - (start.getTime() - now.getTime())
              );
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "上月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              // 获取当前日期
              const now = new Date();
              // 获取上个月的第一天
              const firstDayOfLastMonth = new Date(
                now.getFullYear(),
                now.getMonth() - 1,
                1
              );
              // 获取上个月的最后一天
              const lastDayOfLastMonth = new Date(
                now.getFullYear(),
                now.getMonth(),
                0
              );
              start.setTime(firstDayOfLastMonth.getTime());
              end.setTime(lastDayOfLastMonth.getTime());
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      disabled: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收支记录表格数据
      expensesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        regionId: null,
        regionName: null,
        storeId: null,
        storeName: null,
        typeId: null,
        typeName: null,
        price: null,
        state: null,
        isStatistics: null,
        voucher: null,
        startTime: "",
        endTime: "",
        remark: null,
      },
      searchTime: [],

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入收支名称", trigger: "blur" }, 
        ]
      },
      region: [],
      store: [],
      typeOptions: [
        { label: "收入", value: 1 },
        { label: "支出", value: 2 },
      ],
      typeConfig: {
        1: "收入",
        2: "支出",
      },
      statisticOptions: [
        { label: "是", value: 1 },
        { label: "否", value: 0 },
      ],
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/expenses/importData",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询收支记录列表 */
    getTime() {
      this.queryParams.startTime = this.searchTime[0];
      this.queryParams.endTime = this.searchTime[1];
    },
    getList() {
      this.loading = true;
      listExpenses(this.queryParams).then((response) => {
        this.expensesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    listMemberRegion() {
      listMemberRegion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    changeRegion(value) {
      const selectedOption = this.region.find((item) => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      this.form.regionName = selectedValue;
      listMemberStore({ regionId: value }).then((res) => {
        this.store = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          };
        });
      });
    },
    changeStore(value) {
      const selectedOption = this.store.find((item) => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      this.form.storeName = selectedValue;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        regionId: null,
        regionName: null,
        storeId: null,
        storeName: null,
        typeId: null,
        typeName: null,
        price: null,
        createTime: null,
        updateTime: null,
        state: null,
        isStatistics: null,
        voucher: null,
        remark: null,
        startTime: "",
        endTime: "",
      };
      this.searchTime = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.startTime = "";
      this.queryParams.endTime = "";
      this.searchTime = [];

      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.listMemberRegion();
      this.title = "添加收支记录";
    },
    /** 修改按钮操作   type  1 修改  2 查看*/
    handleUpdate(row, type) {
      this.reset();
      this.disabled = false;
      const id = row.id || this.ids;
      getExpenses(id).then((response) => {
        this.form = response.data;
        this.open = true;

        this.title = "修改收支记录";
        if (type == 2) {
          this.title = "查看收支记录";
          this.disabled = true;
        }
        listMemberRegion().then((res) => {
          this.region = res.data.map((rItem) => {
            return {
              key: rItem.id,
              value: rItem.regionName,
            };
          });
        });
        listMemberStore({ regionId: response.data.regionId }).then((res) => {
          this.store = res.data.map((rItem) => {
            return {
              key: rItem.id,
              value: rItem.storeName,
            };
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateExpenses(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExpenses(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除收支记录编号为"' + ids + '"的数据项？')
        .then(function () {
          return delExpenses(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/system/expenses/export",
        {
          ...this.queryParams,
        },
        `expenses_${new Date().getTime()}.xlsx`
      );
    },
    // 导入按钮操作
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.download('system/user/importTemplate', {
      // }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
